package com.zhkj.txg.module.home.ui

import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.entity.node.BaseNode
import com.google.android.material.tabs.TabLayout
import com.google.gson.Gson
import com.youth.banner.Banner
import com.youth.banner.indicator.CircleIndicator
import com.youth.banner.indicator.RectangleIndicator
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.config.BASE_URL
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.SPUtil
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.txg.R
import com.zhkj.txg.base.CustomApplication
import com.zhkj.txg.module.find.ui.FindArticleDetailActivity
import com.zhkj.txg.module.group.ui.GroupListActivity
import com.zhkj.txg.module.group.ui.PromotionListActivity
import com.zhkj.txg.module.home.adapter.*
import com.zhkj.txg.module.home.entity.*
import com.zhkj.txg.module.home.popup.NewCouponPopupWindow
import com.zhkj.txg.module.home.vm.HomeViewModel
import com.zhkj.txg.module.mine.ui.DiamondActivity
import com.zhkj.txg.module.product.entity.ProductResponse2
import com.zhkj.txg.module.product.ui.ProductDetailActivity2
import com.zhkj.txg.utils.AnimManager
import com.zhkj.txg.utils.GridItemDecoration
import com.zhkj.txg.utils.ImageUtils
import com.zhkj.txg.utils.typeJump
import kotlinx.android.synthetic.*
import kotlinx.android.synthetic.main.fragment_home.*
import kotlin.math.abs


@Suppress("UNCHECKED_CAST")
class HomeFragment : ViewModelFragment<HomeViewModel>() {

    private var refresh = false

    //    private val cateAdapter = HomeCateAdapter2().apply {
//        setOnItemClickListener { _, _, position ->
//            val item = data[position]
//            when (item.jumpType) {
//                0 -> MallActivity.open(requireActivity())                   // 商城
//                1 -> MarketActivity.open(requireActivity())                 // 超市
//                2 -> TopProductActivity.open(requireActivity())             // 9.9尖货
//                3 -> startActivity(Intent(activity, CouponCenterActivity::class.java)) // 领券中心
//                4 -> if (AccountManager.getToken().isEmpty()) LoginActivity.jump2Login(requireActivity())
//                else viewModel.isUserApply() // 商家入驻
//                5 -> WelfareActivity.welfare(requireActivity())             // 天兴购公益
//                6 -> startActivity(Intent(activity, CategoryActivity::class.java)) // 全部分类
//                // 商品二级分类页面
//                7 -> if (!item.params.isNullOrEmpty()) SecondCategory1Activity.goodsCate(
//                    requireActivity(), item.params.toInt()
//                )
//                // 商品三级分类页面
//                8 -> if (!item.params.isNullOrEmpty()) ProductListActivity.categoryOpen(
//                    requireContext(), item.name, item.params.toInt()
//                )
//                else -> Unit
//            }
//        }
//    }
    private val cateAdapter = HomeCateAdapter2().apply {
        setOnItemClickListener { _, _, position ->
            val item = data[position]
            val params = item.params
            if (item.jumpType == 5) {
                DiamondActivity.open(requireActivity())
                return@setOnItemClickListener
            }
            if (params.isNullOrEmpty()) {
                toast("跳转参数为空！")
                return@setOnItemClickListener
            } else when (item.jumpType) {//(0不跳转,1跳转普通商品,2拼团商品,3商品一级分类,4商品二级分类,5会员中心,6店铺)
                1 -> {
                    ProductDetailActivity2.normalProduct(requireContext(), params.toInt(), shopId = CustomApplication.getShopId())
                } // 1跳转普通商品
                2 -> {
                } // 2拼团商品
                3 -> {
                    CategoryActivity.open(requireContext(), params.toInt())
                } // 3商品一级分类
                4 -> {
                    ProductListActivity.categoryOpen(
                        requireContext(), item.name, params.toInt(),
                        CustomApplication.getShopId()
                    )
                } // 4商品二级分类
                5 -> {
                    DiamondActivity.open(requireActivity())
                } // 5会员中心
                6 -> {
                } // 6店铺
                7 -> {
                    EventCommodityActivity.open(requireActivity(), item.name, params.toInt())
                }//活动页面
                else -> Unit
            }
        }
    }

    private val recommendAdapter = HomeRecommendAdapter()
    private val flashSaleAdapter = HomeFlashSaleAdapter()

    private val sellAndGoodAdapter = HomeSellGoodAdapter().apply {
        headerWithEmptyEnable = true
//        loadMoreModule?.setOnLoadMoreListener {
//            viewModel.getHotGoods(AccountManager.getToken())
//        }
    }

    private var shop_id = -1
    private var maxScrollHeight: Float = 0f

    private lateinit var bannerHome: Banner<BannerEntity, HomeBannerAdapter>
    private lateinit var bannerGrass: Banner<GrassEntity, HomeGrassAdapter>
    private lateinit var ivHomeAd: ImageView
    private lateinit var llHomeRecommend: LinearLayout
    private lateinit var llHomeBulletin: ConstraintLayout
    private lateinit var tvHomeBulletinTitle: TextView
    private lateinit var clHomeFlashSale: ConstraintLayout
    private lateinit var llHomeCube: LinearLayout
    private lateinit var llCube2: LinearLayout
    private lateinit var imageCube1: ImageView
    private lateinit var imageCube2: ImageView
    private lateinit var imageCube3: ImageView
    private lateinit var imageCube4: ImageView
    private lateinit var bannerHomeRecommend: Banner<List<RecommendInfo>, HomeBannerRecommendAdapter>
    private val couponPopupWindow: NewCouponPopupWindow by lazy {
        NewCouponPopupWindow(requireActivity().application)
    }

    override fun setViewModel(): HomeViewModel = createViewModel(true)
    override val layoutResId: Int = R.layout.fragment_home

    override fun initUI() {
        sellAndGoodAdapter.setOnItemChildClickListener { adapter, view, position ->  }
        //  计算顶部滚动栏变色的最大高度
        maxScrollHeight = ScreenUtil.getScreenWidth(requireContext()) * 0.63F
        // 设置TitleBar的高度
        titleHome.setFragmentStatusBar()
        // 配置商品的适配器
        with(rvHome) {
            layoutManager = GridLayoutManager(context, 2).apply {
                spanSizeLookup.isSpanIndexCacheEnabled = true
//                initialPrefetchItemCount = 6
            }
            addItemDecoration(
                GridItemDecoration(
                    ScreenUtil.dip(requireContext(), 10),
                    ScreenUtil.dip(requireContext(), 10)
                )
            )
            adapter = sellAndGoodAdapter
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                val llm = layoutManager as GridLayoutManager
                val pos = IntArray(2)
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    // 设置title的透明度
                    val firstItem = llm.findFirstVisibleItemPosition()
                    if (firstItem == 0 && llm.getChildAt(0) != null) {
                        llm.getChildAt(0)!!.getLocationInWindow(pos)
                        if (abs(pos[1]) <= maxScrollHeight) {
                            val alpha = (abs(pos[1]).toFloat() / maxScrollHeight * 255).toInt()
                            titleHome.setDividerVisible(false).setBackgroundColor(Color.argb(alpha, 255, 255, 255))
                            tvSearch.setBackgroundResource(R.drawable.bg_round_white_30dp_transparent)
                            tvHomeShopList.setTextColor(Color.WHITE)
                            titleHome.setDividerVisible(false)
                            ivHomeLocation.setImageResource(R.drawable.ic_location)
                        } else {
                            titleHome.setDividerVisible(true).setBackgroundColor(Color.argb(255, 255, 255, 255))
                            tvSearch.setBackgroundResource(R.drawable.bg_round_gray_100)
                            tvHomeShopList.setTextColor(Color.BLACK)
                            titleHome.setDividerVisible(true)
                            ivHomeLocation.setImageResource(R.drawable.ic_product_location)
                        }
                    }
                    ivHomeTop.visibility = if (firstItem > 10) View.VISIBLE else View.GONE
                }
            })
            refreshHome.setOnRefreshListener { initData() }
        }
        // 设置头布局
        sellAndGoodAdapter.setHeaderView(createHeaderView())
        sellAndGoodAdapter.addChildClickViewIds(R.id.tvAdd)
        sellAndGoodAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.tvAdd) {
                val data = adapter.data[position]
                with(data as SearchProductEntity) {
                    val bottomTab: TabLayout = requireActivity().findViewById<TabLayout>(R.id.bottomTab)
                    val animManager = AnimManager.Builder()
                        .with(requireActivity())
                        .animModule(AnimManager.AnimModule.SMALL) //图片的动画模式，小的或者大的（仿每日优鲜）
                        .startView(view) //开始位置的控件
                        .endView(bottomTab) //结束位置的控件
                        .listener(object : AnimManager.AnimListener {
                            override fun setAnimBegin(a: AnimManager) {}
                            override fun setAnimEnd(a: AnimManager) {}
                        })
                        .imageUrl(image)
                        .build()
                    animManager.startAnim()

                    val map = hashMapOf("goods_id" to id.toString(), "goods_num" to "1", "shop_id" to shop_id.toString())
                    viewModel.addCart(map)
                }
            }
        }
        // 跳转搜索页面
        tvSearch.setOnClickListener {
            SearchActivity.homeOpen(requireActivity(), 0)
        }
        // 跳转门店列表页面
        tvHomeShopList.setOnClickListener {
            val intent = Intent(activity, ShopListActivity::class.java)
            startActivityForResult(intent, 121)
        }
//        ivMessage.setOnClickListener {
//            if (!AccountManager.getToken().isBlank()) {
//                startActivity(Intent(requireContext(), SystemNotificationActivity::class.java))
//            } else LoginActivity.jump2Login(requireActivity())
//        }
        // 跳转回顶部
        ivHomeTop.setOnClickListener {
            rvHome.scrollToPosition(0)
//            rvHome.smoothScrollToPosition(0)
        }

        llHomeBulletin.setOnClickListener {
            homeEntity?.notify?.let { notify ->
                var title = ""
                var content = ""
                notify.forEach {
                    if (tvHomeBulletinTitle.text == it.title) {
                        title = it.title
                        content = it.content
                    }
                }
                layDialog(title, content)
            }
        }
    }

    /**
     * 自定义布局的对话框
     */
    private fun layDialog(title: String, content: String) {
        val view: View = LayoutInflater.from(requireContext()).inflate(
            R.layout.dialog_home_notice, null, false
        )
        val dialog = Dialog(requireContext())
        dialog.setContentView(view)
        dialog.window!!.setBackgroundDrawableResource(android.R.color.transparent)
        val tvNoticeTitle: TextView = view.findViewById(R.id.tvNoticeTitle)
        val tvNoticeContent: TextView = view.findViewById(R.id.tvNoticeContent)
        val tvNotifyClose: TextView = view.findViewById(R.id.tvNotifyClose)
        tvNoticeTitle.text = title
        tvNoticeContent.text = content
        // 取消按钮
        tvNotifyClose.setOnClickListener {
            dialog.dismiss()
        }
        dialog.show()
    }

    private var homeEntity: HomeEntity? = null
    override fun initViewModel() {
        // 热门商品观察
//        viewModel.hotGoodsLiveData.observe(viewLifecycleOwner, Observer { data ->
//            when (data.status) {
//                HttpResponseStatus.Status.START -> Unit
//                HttpResponseStatus.Status.SUCCESS -> data.response?.let {
//                    // 恢复加载状态
//                    if (!it.loadMore) refreshHome.finishRefresh()
//                    else if (it.hasMore) sellAndGoodAdapter.loadMoreModule?.loadMoreComplete()
//                    else sellAndGoodAdapter.loadMoreModule?.loadMoreEnd()
//                    // 添加热卖头部
//                    if (!it.loadMore) sellAndGoodAdapter.addData(HotGoodsHeaderEntity())
//                    // 填充数据
//                    sellAndGoodAdapter.addData(it.data as MutableList<BaseNode>)
//                }
//                HttpResponseStatus.Status.FAILURE -> {
//                    data.exception?.printStackTrace()
//                    toast(data.statusTip)
//                    if (viewModel.page > 1) sellAndGoodAdapter.loadMoreModule?.loadMoreFail()
//                    else refreshHome.finishRefresh(false)
//                }
//            }
//        })
//        viewModel.applyLiveData.observe(viewLifecycleOwner, Observer { response ->
//            handlerResponseStatus(response.status, response.statusTip)
//            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let {
//                MerchantRegisterActivity.open(requireActivity(), it)
//            }
//        })
        viewModel.homeDataLiveData.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let {
                this.homeEntity = it
                setHomeData(it)

                viewModel.searchProduct(
                    token = AccountManager.getToken(),
                    shopId = shop_id,
                    activeType = null,
                    search = "",
                    catId = 0,
                    sort = "weigh",
                    sortAsc = true,
                    recommend = null,
                    restart = true
                )
            }
            refreshHome.finishRefresh()
        })
//        handlerResponseStatus(it.status, it.statusTip)
//            if (it.status == HttpResponseStatus.Status.SUCCESS) {
//                val data = it.response?.data
//                if (data != null) setHomeData(data)
//            } else if (it.status == HttpResponseStatus.Status.FAILURE) {
//                refreshHome.finishRefresh(false)
//            }
        // 账号变更观察者
        viewModel.accountChangeSubscribe().observe(viewLifecycleOwner, Observer { refresh = true })
        // 会员状态变更观察者
        viewModel.memberStatusChangeSubscribe().observe(viewLifecycleOwner, Observer { refresh = true })
        // 退出登录状态观察者
        viewModel.logoutSubscribe().observe(viewLifecycleOwner, Observer { refresh = true })


//         商品列表数据观察者
        viewModel.productListLiveData.observe(this, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.let {
                    // 判断加载状态
//                    if (!it.loadMore) refreshSearch.finishRefresh()
//                    else if (it.hasMore) searchAdapter.loadMoreModule?.loadMoreComplete()
//                    else searchAdapter.loadMoreModule?.loadMoreEnd()
//                    // 数据填充
//                    if (it.loadMore) searchAdapter.addData(it.data)
//                    else searchAdapter.setNewData(it.data)

//                    it.data?.let {
//
//                        data.goods?.goods?.let {
//                            sellAndGoodAdapter.addData(it)
//                        }
//                    }
                    homeEntity?.let { data ->
                        data.goods?.goods?.clear()
                        data.goods?.goods?.addAll(it.data)
                    }

                    homeEntity?.goods?.goods?.let {
                        sellAndGoodAdapter.addData(it)
                    }
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
//                    if (viewModel.page > 1) searchAdapter.loadMoreModule?.loadMoreFail()
//                    else refreshSearch.finishRefresh(false)
                }
            }
        })
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden && refresh) {
            initData()
            refresh = false
        }
    }

    override fun onResume() {
        super.onResume()
        if (refresh) {
            initData()
            refresh = false
        }
        if (shop_id != -1) {
            val shopInfo1 = SPUtil.getInstance().getString(AccountManager.SHOP_INFO)
            val shopInfo2 = try {
                val gson = Gson()
                gson.fromJson<ShopInfo>(shopInfo1, ShopInfo::class.java)
            } catch (e: Exception) {
                null
            }
            if (shopInfo2?.id?.toInt() != shop_id) {
                initData()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 121 && resultCode == -1 && data != null) {
            val shopInfo = data.getStringExtra(AccountManager.SHOP_INFO)
                ?: return
            SPUtil.getInstance().putString(AccountManager.SHOP_INFO, shopInfo)
            initData()
        }
    }

    override fun initData() {


//        val map = hashMapOf("lng" to "120", "lat" to "20")
//        // 首页数据观察
//        viewModel.getHomeData(AccountManager.getToken()).takeIf {
//            !it.hasObservers()
//        }?.observe(viewLifecycleOwner, Observer {
//            handlerResponseStatus(it.status, it.statusTip)
//            if (it.status == HttpResponseStatus.Status.SUCCESS) {
//                val data = it.response?.data
//                if (data != null) setHomeData(data)
//            } else if (it.status == HttpResponseStatus.Status.FAILURE) {
//                refreshHome.finishRefresh(false)
//            }
//        })
        val shopInfo1 = SPUtil.getInstance().getString(AccountManager.SHOP_INFO)
        val shopInfo2 = try {
            val gson = Gson()
            gson.fromJson<ShopInfo>(shopInfo1, ShopInfo::class.java)
        } catch (e: Exception) {
            null
        }
        if (shopInfo2 == null) {
            val intent = Intent(activity, ShopListActivity::class.java)
            startActivityForResult(intent, 121)
        } else {
            shop_id = shopInfo2.id?.toInt()!!
            tvHomeShopList.text = shopInfo2.shop_name
            val map = hashMapOf<String, String>()
            shopInfo2.id.let {
                map["shop_id"] = it
            }
            viewModel.getHomeData(map)

//            val map = hashMapOf("lng" to "120", "lat" to "30")
//            viewModel.getShopList(map).takeIf {
//                !it.hasObservers()
//            }?.observe(viewLifecycleOwner, Observer {
//                handlerResponseStatus(it.status, it.statusTip)
//                if (it.status == HttpResponseStatus.Status.SUCCESS) {
////                val data = it.response?.data
////                if (data != null) setHomeData(data)
//                } else if (it.status == HttpResponseStatus.Status.FAILURE) {
//                    refreshHome.finishRefresh(false)
//                }
//            })

        }

    }


    private fun createHeaderView(): View {
        return layoutInflater.inflate(R.layout.item_home_header, null).apply {
            bannerHome = findViewById(R.id.bannerHome)
            bannerGrass = findViewById(R.id.bannerGrass)
            ivHomeAd = findViewById(R.id.ivHomeAd)
            llHomeRecommend = findViewById(R.id.llHomeRecommend)
            bannerHomeRecommend = findViewById(R.id.bannerHomeRecommend)
            llHomeBulletin = findViewById(R.id.llHomeBulletin)
            tvHomeBulletinTitle = findViewById(R.id.tvHomeBulletinTitle)
            clHomeFlashSale = findViewById(R.id.clHomeFlashSale)
            llHomeCube = findViewById(R.id.llHomeCube)
            llCube2 = findViewById(R.id.llCube2)
            imageCube1 = findViewById(R.id.imageCube1)
            imageCube2 = findViewById(R.id.imageCube2)
            imageCube3 = findViewById(R.id.imageCube3)
            imageCube4 = findViewById(R.id.imageCube4)
//            with(findViewById<ViewPager2>(R.id.rvHomeCate)) {
//                getChildAt(0)?.overScrollMode = View.OVER_SCROLL_NEVER
//                orientation = ViewPager2.ORIENTATION_HORIZONTAL
//                adapter = cateAdapter
//            }
            with(findViewById<RecyclerView>(R.id.rvHomeCate)) {
                layoutManager = GridLayoutManager(requireContext(), 5, GridLayoutManager.VERTICAL, false)
                adapter = cateAdapter
            }

//            with(findViewById<RecyclerView>(R.id.rvHomeRecommend)) {
//                layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
//                addItemDecoration(
//                    GridItemDecoration(
//                        ScreenUtil.dip(requireContext(), 5),
//                        ScreenUtil.dip(requireContext(), 5)
//                    )
//                )
//                adapter = recommendAdapter
//            }

            recommendAdapter.setOnItemClickListener { adapter, view, position ->
                ProductDetailActivity2.normalProduct(context, recommendAdapter.data[position].id.toInt(), shopId = shop_id)
            }

            with(findViewById<RecyclerView>(R.id.rvHomeFlashSale)) {
                layoutManager = GridLayoutManager(requireContext(), 4, GridLayoutManager.VERTICAL, false)
                addItemDecoration(
                    GridItemDecoration(
                        ScreenUtil.dip(requireContext(), 5),
                        ScreenUtil.dip(requireContext(), 5)
                    )
                )
                adapter = flashSaleAdapter
            }
            flashSaleAdapter.setOnItemClickListener { adapter, view, position ->
                ProductDetailActivity2.normalProduct(context, flashSaleAdapter.data[position].id.toInt(), shopId = shop_id)
            }


            with(findViewById<TabLayout>(R.id.tabHome)) {
                addTab(newTab().setCustomView(R.layout.item_home_tab_sell))
                addTab(newTab().setCustomView(R.layout.item_home_tab_next_sell))
                addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                    override fun onTabReselected(tab: TabLayout.Tab?) = Unit

                    override fun onTabUnselected(tab: TabLayout.Tab?) {
                        tab?.customView?.isSelected = false
                    }

                    override fun onTabSelected(tab: TabLayout.Tab?) {
                        tab?.customView?.isSelected = true
                        viewModel.homeDataLiveData.value?.response?.data?.let {
                            sellAndGoodAdapter.nodeReplaceChildData(
                                it.sellData!! as BaseNode,
                                if (tab?.position == 0) it.sell else it.nextSell
                            )
                        }
                    }
                })
            }
            findViewById<View>(R.id.llHomeRecommend).setOnClickListener {
                EventCommodityActivity.openRecommend(requireActivity(), 0)
            }
            findViewById<View>(R.id.tvHomeFlashSaleMore).setOnClickListener {
                EventCommodityActivity.openRecommend(requireActivity(), 1)
            }
            findViewById<View>(R.id.btnHomeGroup).setOnClickListener { GroupListActivity.startActivity(activity) }
            findViewById<View>(R.id.btnHomePromotion).setOnClickListener { PromotionListActivity.startActivity(activity) }
            // 配置轮播图
            bannerHome.setIndicator(CircleIndicator(context)).addBannerLifecycleObserver(this@HomeFragment)
                .setAdapter(HomeBannerAdapter(context)).setOnBannerListener { data, _ ->
                    (data as? BannerEntity)?.let {
                        typeJump(requireContext(), it.jumpType ?: 0, it.params, it.title)
                    }
                }

            bannerHomeRecommend.setIndicator(RectangleIndicator(context)).addBannerLifecycleObserver(this@HomeFragment)
                .setAdapter(HomeBannerRecommendAdapter(context)).setOnBannerListener { data, _ ->

                }
            // 配置种草页面
            bannerGrass.setOrientation(Banner.VERTICAL).setUserInputEnabled(false)
                .addBannerLifecycleObserver(this@HomeFragment)
                .setAdapter(HomeGrassAdapter(context)).setOnBannerListener { data, _ ->
                    (data as? GrassEntity)?.let {
                        FindArticleDetailActivity.openDetail(context, it.id)
                    }
                }
        }
    }

    private fun setHomeData(data: HomeEntity) {
        // 设轮播图
        bannerHome.setDatas(data.banner).start()
        // 设置分类
        cateAdapter.setNewData(data.navigation)
        //设置通知
        data.notify.let {
            if (it.size == 0) {
                llHomeBulletin.visibility = View.GONE
            } else {
                llHomeBulletin.visibility = View.VISIBLE
                tvHomeBulletinTitle.text = it.get(0).title
            }
        }
        // 设置掌柜推荐
        data.goods?.recommend?.let {
            if (it.size == 0) {
                llHomeRecommend.visibility = View.GONE
            } else {
                llHomeRecommend.visibility = View.VISIBLE
                val recommends = mutableListOf<List<RecommendInfo>>()
                if (it.size <= 3) {
                    recommends.add(it)
                    bannerHomeRecommend.stop()
                    bannerHomeRecommend.setDatas(recommends).start()
                } else {
                    for (i in 0..it.size / 3) {
                        val fromIndex = i * 3
                        val toIndex = (i + 1) * 3
                        if (toIndex > it.size) {
                            recommends.add(it.subList(fromIndex, it.size))
                        } else {
                            recommends.add(it.subList(fromIndex, toIndex))
                        }
                    }
                    bannerHomeRecommend.stop()
                    bannerHomeRecommend.setDatas(recommends).start()
                }
            }
        }
        //设置限时抢购
        data.goods?.promotion?.let {
            if (it.size == 0) {
                clHomeFlashSale.visibility = View.GONE
            } else {
                clHomeFlashSale.visibility = View.VISIBLE
                flashSaleAdapter.setNewData(it)
            }
        }
        //魔方
        data.cube.let {
            val size = it.size
            if (size == 0) {
                llHomeCube.visibility = View.GONE
            } else {
                llHomeCube.visibility = View.VISIBLE
                if (size == 1) {
                    imageCube2.visibility = View.GONE
                    llCube2.visibility = View.GONE
                    ImageUtils.loadImage(
                        requireActivity(), imageCube1,
                        if (it[0].image.startsWith("http")) it[0].image else BASE_URL + it[0].image
                    )
                    imageCube1.tag = it[0]
                } else if (size == 2) {
                    imageCube2.visibility = View.GONE
                    imageCube4.visibility = View.GONE
                    ImageUtils.loadImage(
                        requireActivity(), imageCube1,
                        if (it[0].image.startsWith("http")) it[0].image else BASE_URL + it[0].image
                    )
                    imageCube1.tag = it[0]
                    ImageUtils.loadImage(
                        requireActivity(), imageCube3,
                        if (it[1].image.startsWith("http")) it[1].image else BASE_URL + it[1].image
                    )
                    imageCube3.tag = it[1]

                } else if (size == 3) {
                    imageCube2.visibility = View.GONE
                    ImageUtils.loadImage(
                        requireActivity(), imageCube1,
                        if (it[0].image.startsWith("http")) it[0].image else BASE_URL + it[0].image
                    )
                    imageCube1.tag = it[0]
                    ImageUtils.loadImage(
                        requireActivity(), imageCube3,
                        if (it[1].image.startsWith("http")) it[1].image else BASE_URL + it[1].image
                    )
                    imageCube3.tag = it[1]
                    ImageUtils.loadImage(
                        requireActivity(), imageCube4,
                        if (it[2].image.startsWith("http")) it[2].image else BASE_URL + it[2].image
                    )
                    imageCube4.tag = it[2]
                } else {
                    ImageUtils.loadImage(
                        requireActivity(), imageCube1,
                        if (it[0].image.startsWith("http")) it[0].image else BASE_URL + it[0].image
                    )
                    imageCube1.tag = it[0]
                    ImageUtils.loadImage(
                        requireActivity(), imageCube2,
                        if (it[1].image.startsWith("http")) it[1].image else BASE_URL + it[1].image
                    )
                    imageCube2.tag = it[1]
                    ImageUtils.loadImage(
                        requireActivity(), imageCube3,
                        if (it[2].image.startsWith("http")) it[2].image else BASE_URL + it[2].image
                    )
                    imageCube3.tag = it[2]
                    ImageUtils.loadImage(
                        requireActivity(), imageCube4,
                        if (it[3].image.startsWith("http")) it[3].image else BASE_URL + it[3].image
                    )
                    imageCube4.tag = it[3]
                }

                imageCube1.setOnClickListener {
                    val cube: Cube = imageCube1.tag as Cube
                    typeJump(requireContext(), cube.jump_type ?: 0, cube.params, cube.title)
                }
                imageCube2.setOnClickListener {
                    val cube: Cube = imageCube2.tag as Cube
                    typeJump(requireContext(), cube.jump_type ?: 0, cube.params, cube.title)
                }
                imageCube3.setOnClickListener {
                    val cube: Cube = imageCube3.tag as Cube
                    typeJump(requireContext(), cube.jump_type ?: 0, cube.params, cube.title)
                }
                imageCube4.setOnClickListener {
                    val cube: Cube = imageCube4.tag as Cube
                    typeJump(requireContext(), cube.jump_type ?: 0, cube.params, cube.title)
                }

            }
        }
        // 设置广告+
        data.activity?.image?.let {
            ImageUtils.loadRoundCornerImage(this, ivHomeAd, it)
            ivHomeAd.visibility = View.VISIBLE
        }

        data.activity?.let { activity ->

            // 会员广告点击
            ivHomeAd.setOnClickListener {
                if (activity.params != null) {
                    typeJump(requireContext(), activity.jump_type ?: 0, activity.params, activity.title)
                } else {
                    toast("跳转参数为空")
                }
            }
        }

//        ImageUtils.loadImage(this, ivGroup, data.group_image ?: "")
//        ImageUtils.loadImage(this, ivGrass, data.spike_image ?: "")
        // 设置种草数据
        bannerGrass.setDatas(data.grass).start()
        // 设置特卖数据
        sellAndGoodAdapter.setNewData(mutableListOf(data.sellData!!))
        // 填充数据
        sellAndGoodAdapter.addData(HotGoodsHeaderEntity())
//        data.goods?.goods?.let {
//            sellAndGoodAdapter.addData(it)
//        }
//        sellAndGoodAdapter.addData(data.goods?.goods as MutableList<BaseNode>)
        // 判断是否是新用户，弹出窗口
        if (data.coupon != null) {
            couponPopupWindow.setData(data.coupon)
            couponPopupWindow.showPopupWindow()
        }
    }
}